const path = require('path')
const fs = require('fs')
const { v4: uuidv4 } = require('uuid')
const { writeFile } = require('../utils/fileUtils')

function saveToLocal(file) {
  const today = new Date()
  const folder = `${today.getFullYear()}/${today.getMonth() + 1}/${today.getDate()}`

  const ext = path.extname(file.originalname)
  const filename = `${uuidv4()}${ext}`

  writeFile(file, folder, filename);
  return {
    url: `/uploads/${folder}/${filename}`,
    name: filename
  }
}

/**
 * 删除本地文件
 * @param {string} imageUrl - 相对路径，如 'uploads/xxx.jpg'
 * @returns {Promise<boolean>} - 是否删除成功（不存在视为成功）
 */
function delLocalFile(imageUrl) {
  return new Promise((resolve, reject) => {
    const filePath = path.resolve(__dirname, '../public', imageUrl);

    fs.access(filePath, fs.constants.F_OK, (err) => {
      if (err) {
        console.log(`[跳过删除] 文件不存在: ${filePath}`);
        return resolve(true);
      }

      fs.unlink(filePath, (err) => {
        if (err) {
          console.error(`[删除失败] ${filePath}:`, err.message);
          return resolve(false); // 不抛出 reject，避免影响主流程
        } else {
          console.log(`[已删除图片文件] ${filePath}`);
          return resolve(true);
        }
      });
    });
  });
}

module.exports = {
  saveToLocal,
  delLocalFile
}
